import { createRouter, createWebHistory } from 'vue-router'
import dynamicConst from '@/router/dynamicConst'
import { ref } from 'vue'
import { useLoginStore } from '@/stores/index'

export const Layout = () => import("@/layout/index.vue");

const modules = import.meta.glob("../views/**/**.vue");

/**
 * 静态路由
 */
const constantRoutes = [
  {
    path: "/login",
    name: 'login',
    component: () => import('@/views/login/login.vue')
  },
  {
    path: "/",
    name: '首页',
    component: Layout,
    redirect: "/dashboard",
    children: [
      {
        name: '首页',
        path: '/dashboard',
        component: () => import('@/components/home/dashboard.vue')
      },
      // {
      //   path: 'admin',
      //   name: 'admin',
      //   component: () => import('../views/users/index.vue')
      // },
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes: constantRoutes
})

// 本地缓存路由信息
let initLoad: any = []
// 判断是否首次加载路由
const initStatus = ref(true)
// 导航钩子
router.beforeEach((to: any, from: any, next: any) => {
  const token = useLoginStore().getAccessToken()
  // 校验是否登录
  if(!token){
    // 未登录路由跳转登录页
    if(to.path === '/login'){
      return next();
    }else{
      return next('/login')
    }
  }else{
    // 已登录动态生成路由
    if(initStatus.value){
      if(!initLoad.length){
        initLoad = initRouter()
      }
      // 进行追加路由
      initLoad.forEach((route:any) => {
        router.addRoute(route);
      });
      initStatus.value = false
      // 当添加完成后，直接进行一次重定向
      return next(to.path);
    }
  }
  next()
})
// 初始化路由
function initRouter() {
  const menuRule = dynamicConst.map((menu: any) => {
      let route = {
          path: menu.path,
          name: menu.title,
          component: Layout,
          children: processChildren(menu.children),
      }
      return route;
  });
  return menuRule;
}
// 递归处理children子节点
function processChildren(children: any) {
  if (!children || children.length === 0) {
      return [];
  }
  return children.map((child: any) => {
      let route = {
          path: child.path,
          name: child.title,
          component: modules[`../views${child.component}`],
          children: processChildren(child.children),
      }
      return route;
  });
}

export default router
